import subprocess
import re
import os
from typing import List

def checkFileExist(path:str) ->bool :
    check=os.path.isfile(path)
    return check

def checkDirExist(path:str) -> bool:
    check=os.path.isdir(path)
    return check

def getFilesNameFromDir(DirPath:str)-> List[str]:
    if checkDirExist(DirPath):
        pathDir=os.listdir(DirPath)
        return pathDir
    else:
        print("the DirPath isn't exist")

def getSolVersionFromFile(filePath:str)->str:
    '''
    get the useful version of the .sol file
    '''
    pattern='[\\d]+(\\.[\\d]+)(\\.[\\d]+)'
    with open(filePath,'r',encoding='utf-8') as f:
        content = f.read()

    result=re.search(pattern,content)
    if result!=None:
        solv=result.group()

        if solv<"0.4.26":
            solv="0.4.26"
        elif solv<"0.5.17":
            solv="0.5.17"
        elif solv<"0.6.12":
            solv="0.6.12"
        elif solv<="0.7.6":
            solv="0.7.6"
        elif solv<="0.8.4":
            solv="0.8.4"
        else:
            return "None"

        return solv
    return "None"

def useMythrilDectectSol(mythPath:str,filePath:str,solv:str,outputPath:str):
    '''
    use mythril to detect .sol file from filePath and output result to outputPath
    '''
    if solv!="None":
        command="python3 "+mythPath+" analyze "+filePath+" --solv"+" "+solv
    else:
        command="python3 "+mythPath+" analyze "+filePath

    child1=subprocess.Popen(command,shell=True,stdout=subprocess.PIPE)
    output=child1.stdout.read()
    outputstr=output.decode("utf-8")
    # if the sol is safe ,don't output
    if outputstr!="The analysis was completed successfully. No issues were detected.\n\n":
        fileName=filePath.split("/")[-1]
        with open(outputPath+"/"+fileName,"a") as f:
            f.write(outputstr)
    
    child1.kill()



def useMythrilDetectFileInDir(mythPath:str,DirPath:str,outputPath:str):
    files=getFilesNameFromDir(DirPath)
    for file in files:
        filePath=DirPath+"/"+file
        solv=getSolVersionFromFile(filePath)
        try:
            useMythrilDectectSol(mythPath,filePath,solv,outputPath)
        except Exception as e:
            print("%s doesn't run,err is %s"%(filePath,e))
            continue



# mythPath="/home/hello/smartcontract/mythril-develop/myth"
# solDir="/home/hello/Desktop/testfile"
# outputDir="/home/hello/Desktop/testfileDetect"
# useMythrilDetectFileInDir(mythPath,solDir,outputDir)